package com.github.jameszbl.toolkits

import android.Manifest.permission.*
import android.annotation.SuppressLint
import android.annotation.TargetApi
import android.app.PendingIntent
import android.content.*
import android.content.pm.PackageManager.PERMISSION_DENIED
import android.content.pm.ShortcutInfo
import android.content.pm.ShortcutManager
import android.graphics.drawable.Icon
import android.hardware.biometrics.BiometricPrompt
import android.net.wifi.WifiManager
import android.os.Build
import android.os.Bundle
import android.text.format.Formatter
import android.view.View
import android.widget.Toast
import android.widget.Toast.LENGTH_LONG
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat.requestPermissions
import com.google.android.gms.common.api.CommonStatusCodes
import com.google.android.gms.vision.barcode.Barcode

class MainActivity : AppCompatActivity() {

    companion object {
        const val R_QR = 0
        const val R_PERMISSION = 1
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        startChargeService()
        checkPermissions()
//        requestFingerPrint()
    }

    @TargetApi(Build.VERSION_CODES.M)
    override fun onResume() {
        super.onResume()
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun checkPermissions() {
        val permissions = arrayOf(
            CAMERA,
            READ_EXTERNAL_STORAGE,
            WRITE_EXTERNAL_STORAGE,
            READ_PHONE_STATE,
            NFC
        )
        if (PERMISSION_DENIED in permissions.map { checkSelfPermission(it) }) {
            requestPermissions(
                this,
                permissions,
                R_PERMISSION
            )
            requestPermissions(this, permissions, R_PERMISSION)
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        when (requestCode) {
            R_PERMISSION -> {
                if (grantResults.isEmpty() || PERMISSION_DENIED in grantResults) {
                    checkPermissions()
                }
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    @TargetApi(Build.VERSION_CODES.P)
    private fun requestFingerPrint() {
        BiometricPrompt.Builder(this).setTitle(getString(R.string.authentication_title))
            .setNegativeButton(
                getString(R.string.cancel),
                mainExecutor,
                DialogInterface.OnClickListener { dialog, which -> onError() })
            .build()
            .authenticate(cancelSignal(), mainExecutor, authenticationCallback())
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private fun cancelSignal(): android.os.CancellationSignal {
        return android.os.CancellationSignal()
    }

    @TargetApi(Build.VERSION_CODES.O)
    private fun onError() {
        finish()
    }

    @TargetApi(Build.VERSION_CODES.P)
    private fun authenticationCallback(): BiometricPrompt.AuthenticationCallback {
        return object : BiometricPrompt.AuthenticationCallback() {
            override fun onAuthenticationFailed() {
                super.onAuthenticationFailed()
                onError()
            }

            override fun onAuthenticationError(errorCode: Int, errString: CharSequence?) {
                super.onAuthenticationError(errorCode, errString)
                onError()
            }
        }
    }

    @SuppressLint("ShortAlarm")
    @TargetApi(Build.VERSION_CODES.O)
    private fun startChargeService() {
        val intent = Intent(this, BootReceiver::class.java)
        sendBroadcast(intent)
    }

    fun showIp(v: View) {
        Toast.makeText(this, getIp(), LENGTH_LONG).show()
    }

    fun gotoSettings(v: View) {
        val intent = Intent(this, SettingsActivity::class.java)
        startActivity(intent)
    }

    fun gotoCapture(v: View) {
        val intent = Intent(this, CameraActivity::class.java)
        startActivity(intent)
    }

    @Suppress("DEPRECATION")
    private fun getIp(): String {
        val wm: WifiManager =
            applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
        val ip = wm.connectionInfo.ipAddress
        return Formatter.formatIpAddress(ip)
    }

    fun gotoQr(v: View) {
        val intent = Intent(this, QrActivity::class.java)
        startActivityForResult(intent, R_QR)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        when (requestCode) {
            R_QR -> {
                if (resultCode == CommonStatusCodes.SUCCESS) {
                    val barcode = data?.getParcelableExtra<Barcode>("barcode")?.displayValue
                    barcode?.let {
                        Toast.makeText(this, it, LENGTH_LONG).show()
                        val clipboardManager =
                            getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
                        clipboardManager.primaryClip = ClipData.newPlainText("", barcode)
                    }
                }
            }
            else -> super.onActivityResult(requestCode, resultCode, data)
        }
    }

    @RequiresApi(Build.VERSION_CODES.O)
    fun createShortcuts(v: View) {
        val shortcutManager = getSystemService(ShortcutManager::class.java)
        if (shortcutManager!!.isRequestPinShortcutSupported) {
            val pinShortcutInfo =
                ShortcutInfo.Builder(applicationContext, "nfc")
                    .setShortLabel("NFC")
                    .setIcon(Icon.createWithResource(applicationContext, R.mipmap.ic_launcher))
                    .setIntent(
                        Intent()
                            .setAction("nfc")
                            .setPackage("com.github.jameszbl.toolkits")
                            .setClass(applicationContext, NFCActivity::class.java)
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                    ).build()
            val pinnedShortcutCallbackIntent =
                shortcutManager.createShortcutResultIntent(pinShortcutInfo)
            val successCallback = PendingIntent.getBroadcast(
                applicationContext, /* request code */ 0,
                pinnedShortcutCallbackIntent, /* flags */ 0
            )
            shortcutManager.requestPinShortcut(
                pinShortcutInfo,
                successCallback.intentSender
            )
        }
    }
}
